package com.aizuda.boot.modules.business.performancePlan.controller;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.performancePlan.dto.CurrencyAmountDTO;
import com.aizuda.boot.modules.business.performancePlan.dto.CurrencyConversionRequestDTO;
import com.aizuda.boot.modules.business.performancePlan.dto.CurrencyConversionResponseDTO;
import com.aizuda.boot.modules.third.openApi.ExchangeRateApiController;
import com.aizuda.boot.modules.third.openApi.dto.ExchangeRateRequest;
import com.alibaba.fastjson.JSONObject;
import com.aizuda.core.api.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 货币转换控制器
 *
 * @author yangshen
 * @date 2025-08-04
 */
@Slf4j
@RestController
@RequestMapping("/currency-conversion")
@RequiredArgsConstructor
@Validated
@Tag(name = "货币转换管理", description = "货币转换和汇总相关接口")
public class CurrencyConversionController {

    private final ExchangeRateApiController exchangeRateApiController;

    @PostMapping("/convert-to-cny")
    @Operation(summary = "多货币转换为人民币并汇总", 
               description = "将不同货币的金额统一转换为人民币并计算总金额")
    public ApiResult<CurrencyConversionResponseDTO> convertToCny(
            @Valid @RequestBody CurrencyConversionRequestDTO request) {
        
        try {
            log.info("开始进行货币转换，货币数量: {}", request.getCurrencies().size());
            
            CurrencyConversionResponseDTO response = new CurrencyConversionResponseDTO();
            List<CurrencyConversionResponseDTO.ConversionDetailDTO> details = new ArrayList<>();
            BigDecimal totalAmount = BigDecimal.ZERO;
            
            for (CurrencyAmountDTO currencyAmount : request.getCurrencies()) {
                CurrencyConversionResponseDTO.ConversionDetailDTO detail = 
                    new CurrencyConversionResponseDTO.ConversionDetailDTO();
                
                detail.setOriginalAmount(currencyAmount.getAmount());
                detail.setOriginalCurrency(currencyAmount.getCurrency());
                
                BigDecimal convertedAmount;
                BigDecimal exchangeRate = BigDecimal.ONE;
                
                // 如果已经是人民币，则不需要转换
                if ("CNY".equalsIgnoreCase(currencyAmount.getCurrency())) {
                    convertedAmount = currencyAmount.getAmount();
                    exchangeRate = BigDecimal.ONE;
                    log.info("货币已经是CNY，无需转换，金额: {}", convertedAmount);
                } else {
                    // 调用汇率转换接口
                    ExchangeRateRequest exchangeRequest = new ExchangeRateRequest();
                    exchangeRequest.setFromCode(currencyAmount.getCurrency());
                    exchangeRequest.setToCode("CNY");
                    exchangeRequest.setMoney(currencyAmount.getAmount());
                    
                    log.info("调用汇率转换接口，从 {} 转换 {} 到 CNY", 
                            currencyAmount.getCurrency(), currencyAmount.getAmount());
                    
                    SingleResponse<Map<String, Object>> exchangeResponse = 
                        exchangeRateApiController.convertExchangeRate(exchangeRequest);
                    
                    if (exchangeResponse.isSuccess()) {
                        Map<String, Object> data = exchangeResponse.getData();
                        
                        // 解析汇率转换结果
                        if (data != null && data.containsKey("data")) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> resultData = (Map<String, Object>) data.get("data");
                            
                            if (resultData != null && resultData.containsKey("money")) {
                                String convertedAmountStr = resultData.get("money").toString();
                                convertedAmount = new BigDecimal(convertedAmountStr);
                                
                                // 计算汇率
                                if (currencyAmount.getAmount().compareTo(BigDecimal.ZERO) > 0) {
                                    exchangeRate = convertedAmount.divide(currencyAmount.getAmount(), 6, RoundingMode.HALF_UP);
                                }
                                
                                log.info("汇率转换成功，{} {} = {} CNY，汇率: {}", 
                                        currencyAmount.getAmount(), currencyAmount.getCurrency(), 
                                        convertedAmount, exchangeRate);
                            } else {
                                log.error("汇率转换返回数据格式异常，缺少money字段");
                                return ApiResult.failed("汇率转换失败：返回数据格式异常");
                            }
                        } else {
                            log.error("汇率转换返回数据格式异常，缺少data字段");
                            return ApiResult.failed("汇率转换失败：返回数据格式异常");
                        }
                    } else {
                        log.error("汇率转换失败，错误信息: {}", exchangeResponse.getMessage());
                        return ApiResult.failed("汇率转换失败：" + exchangeResponse.getMessage());
                    }
                }
                
                detail.setConvertedAmount(convertedAmount);
                detail.setExchangeRate(exchangeRate);
                details.add(detail);
                
                totalAmount = totalAmount.add(convertedAmount);
            }
            
            response.setTotalAmountCny(totalAmount.setScale(2, RoundingMode.HALF_UP));
            response.setConversionDetails(details);
            
            log.info("货币转换完成，总金额: {} CNY", response.getTotalAmountCny());
            return ApiResult.ok(response);
            
        } catch (Exception e) {
            log.error("货币转换异常", e);
            return ApiResult.failed("货币转换异常：" + e.getMessage());
        }
    }
}